<template>
  <a-spin :spinning="spinning3" class="bg_white">
    <div>
      <a-button type="primary" @click="addDept" class="margin_bottom">
        <a-icon type="user-add" />创建会议
      </a-button>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        bordered
        :rowKey="
          (record, index) => {
            return index;
          }
        "
      >
        <span slot="status" slot-scope="text, record">
          <span v-show="record.status == 1">已结束</span>
          <span v-show="record.status == 2">进行中</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <el-button type="text" size="mini" @click="ParticipantClick(record)"
            >参会人信息</el-button
          >
        </span>
      </a-table>

      <a-modal
        v-model="modelVisible"
        title="部门列表"
        on-ok="handleOk"
        width="50%"
        :footer="null"
        @cancel="noMoelSelect"
      >
        <a-row>
          <a-col :span="8">
            <a-tree
              style="
                min-width: 170px !important;
                margin-top: 10px;
                max-height: 400px;
                overflow-y: auto;
              "
              :tree-data="nodeData"
              :autoExpandParent="true"
              :defaultExpandParent="true"
              :replace-fields="replaceFields"
              :defaultExpandedKeys="[nodeData[0].depId]"
              show-icon
              @select="selectDept"
            >
            </a-tree>
          </a-col>

          <a-col :span="16">
            <a-spin :spinning="spinning2">
              <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
              >
                <a-form-model-item label="会议主题" prop="confTitle">
                  <a-input v-model="form.confTitle" type="textarea" />
                </a-form-model-item>
                <a-form-model-item label="是否邀请主叫" prop="inviteCaller">
                  <a-switch v-model="form.inviteCaller" />
                </a-form-model-item>
                <a-form-model-item label="邀请人" prop="inviteUserIds">
                  <div style="min-height: 100px; max-height: 400px">
                    <div :style="{ borderBottom: '1px solid #E9E9E9' }">
                      <a-checkbox
                        indeterminate="true"
                        v-model="checkAll"
                        @change="onCheckAllChange"
                        >全选</a-checkbox
                      >
                    </div>

                    <a-checkbox-group
                      v-model="checkedList2"
                      @change="change333"
                      style="width: 200px; height: 100%; overflow: auto"
                    >
                      <div v-for="item in checkedList" :key="item">
                        <a-checkbox
                          :value="item.unionid"
                          style="height: 30px !important"
                          >&nbsp;&nbsp;{{ item.name }}</a-checkbox
                        >
                      </div>
                    </a-checkbox-group>
                  </div>
                </a-form-model-item>
                <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
                  <a-button
                    type="primary"
                    @click="onSubmit"
                    :loading="loading2"
                  >
                    提交
                  </a-button>
                  <a-button style="margin-left: 10px" @click="resetForm">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-form-model>
            </a-spin>
          </a-col>
        </a-row>
      </a-modal>
    </div>
  </a-spin>
</template>

<script>
import api from "@/api/cmeduGateway";
import contacts from "@/api/organizations";

const columns = [
  {
    title: "会议主题",
    dataIndex: "title",
    width: 100, 
  },
  {
    title: "会议创建人",
    dataIndex: "creatorNick",
    width: 80, 
  },
  {
    title: "会议链接",
    dataIndex: "externalLinkUrl",
  },

  

  {
    title: "会议邀请人数",
    dataIndex: "invitedNum",
    width: 100, 
  },

  {
    title: "开始时间",
    dataIndex: "startTime",
    scopedSlots: { customRender: "startTime" },
    width: 160, 
  },
  
  {
    title: "结束时间",
    dataIndex: "endTime",
    scopedSlots: { customRender: "endTime" },
    width: 160, 
  },
  
  {
    title: "会议时长(毫秒)",
    dataIndex: "confDuration",
    width: 160, 
  },

  {
    title: "会议code",
    dataIndex: "roomCode",
    width: 160, 
  },

  {
    title: "会议状态",
    dataIndex: "status",
    scopedSlots: { customRender: "status" },
    width: 100, 
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    width: 100, 
  },
];

const x = 3;
const y = 2;
const z = 1;
const gData = [];

const generateData = (_level, _preKey, _tns) => {
  const preKey = _preKey || "0";
  const tns = _tns || gData;

  const children = [];
  for (let i = 0; i < x; i++) {
    const key = `${preKey}-${i}`;
    tns.push({ title: key, key, scopedSlots: { title: "title" } });
    if (i < y) {
      children.push(key);
    }
  }
  if (_level < 0) {
    return tns;
  }
  const level = _level - 1;
  children.forEach((key, index) => {
    tns[index].children = [];
    return generateData(level, key, tns[index].children);
  });
};
generateData(z);

const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: key });
    if (node.children) {
      generateList(node.children);
    }
  }
};
generateList(gData);

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
export default {
  data() {
    return {
      checkAll: false,
      checkedList: [],
      checkedList2: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      other: "",
      form: {
        confTitle: "",
        inviteCaller: false,
        inviteUserIds: "",
      },
      rules: {
        confTitle: [
          { required: true, message: "请输入会议主题", trigger: "blur" },
        ],
      },
      spinning3: false,
      loading2: false,
      visible: false,
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      gData,
      data: [],
      loading: true,
      columns,
      selectedRowKeys: [],
      keyWord: "",
      conDetalObj: {},
      modelVisible: false,
      replaceFields: {
        title: "name",
        key: "depId",
        child: "children",
      },
      nodeData: [{}],
      spinning2: false,
      unionid: "iPQgqbmYWviitSnf65C0CpyQiEiE",
    };
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        onSelection: this.onSelection,
      };
    },
  },
  mounted() {
    this.initData();
    this.getuserInfo();
  },
  methods: {
    ParticipantClick(val) {
      this.$router.push({
        path: "ParticipantInformation",
        query: { meetingId: val.conferenceId },
      });
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading2 = true;
          let data = {
            confTitle: this.form.confTitle,
            inviteCaller: this.form.inviteCaller,
            inviteUserIds: this.checkedList2,
            userId: this.unionid,
          };
          api.createMeeting(data).then((res) => {
            this.addConInfo(res.data);
            // if (res.data.errcode == 0) {

            // }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    onCheckAllChange(e) {
      this.checkedList2 = e.target.checked
        ? this.checkedList.map((item) => item.unionid)
        : [];
      this.indeterminate = false;
    },
    async getuserInfo() {
      let data2 = {
        language: "zh_CN",
        userid: localStorage.getItem("dingtalk_user_id"),
      };
      let res2 = await api.getUserDetail(data2);
      if (res2.data.errcode == 0) {
        this.unionid = res2.data.result.unionid;
      }
    },
    formatData(time) {
      var date = new Date(time);

      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },

    async addConInfo(info) {
      let that = this;
      let id = localStorage.getItem("loginuserId");
      info.create_user_id = id;
      info.create_time = this.getNowDate();
      info.conference_theme = this.form.confTitle;
      let res = await api.addMeeting(info);
      if (res.data.errcode == 0) {
        this.$message.success("创建会议成功");
        this.loading2 = false;
        this.modelVisible = false;
        setTimeout(function () {
          that.initData();
          // 时间间隔
        }, 1000);
      }
    },

    // 格式化日对象
    getNowDate() {
      var date = new Date();
      var sign2 = ":";
      var year = date.getFullYear(); // 年
      var month = date.getMonth() + 1; // 月
      var day = date.getDate(); // 日
      var hour = date.getHours(); // 时
      var minutes = date.getMinutes(); // 分
      var seconds = date.getSeconds(); //秒
      var weekArr = [
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
        "星期天",
      ];
      var week = weekArr[date.getDay()];
      // 给一位数的数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        sign2 +
        minutes +
        sign2 +
        seconds
      );
    },

    change333() {
      // console.log(this.checkedList2)
    },

    async selectDept(params, e) {
      this.spinning2 = true;
      let depId = e.selectedNodes[0].data.props.depId;
      let data = {
        cursor: 0,
        contain_access_limit: false,
        size: 10,
        order_field: "modify_desc",
        language: "zh_CN",
        dept_id: depId,
      };
      let res = await api.getUserData(data);

      if (res.data.errcode == 0) {
        this.checkedList = res.data.result.list;
        this.spinning2 = false;
      }
      // let list = [];
      // let res = await api.getUserInfoByEmpId(data);
      // if (res.data.errcode == 0) {
      //   this.checkedList = res.data.result.list;
      // }
      // let arr = [];
      // this.checkedList = [];
      // for (let index = 0; index < list.length; index++) {
      //   let data2 = {
      //     language: "zh_CN",
      //     userid: list[index].userid,
      //   };

      //   let res2 = await api.getUserDetail(data2);
      //   if (res2.data.errcode == 0) {
      //     arr.push(res2.data.result);
      //   }
      // }
      // this.checkedList = arr;
    },
    async addDept() {
      this.spinning3 = true;
      let data = {
        token: "",
        deptId: 1,
      };
      let res = await contacts.getDingTree(data);
      let arr = [];
      arr.push(res.data);
      this.nodeData = arr;
      this.spinning3 = false;
      this.modelVisible = true;
    },
    async initData() {
      let res = await api.getMeetingId();
      if (res.data.errcode == 0) {
        this.data = res.data.rows;
        this.data = this.data.reverse();
        for (let index = 0; index < this.data.length; index++) {
          this.data[index].startTime = this.formatData(
            this.data[index].startTime
          );
          if (this.data[index].endTime) {
            this.data[index].endTime = this.formatData(
              this.data[index].endTime
            );
          }
        }
        this.loading = false;
      }
    },
    async getDtail(val) {
      let res2 = await api.getMeeting(val.conferenceId);

      this.conDetalObj = res2.data.confInfo;
      this.conDetalObj.startTime = this.getFormatData(
        this.conDetalObj.startTime
      );
      this.conDetalObj.endTime = this.getFormatData(this.conDetalObj.endTime);

      this.conDetalObj.confDuration = this.formatDuring(
        this.conDetalObj.confDuration
      );

      this.visible = true;
    },
    getFormatData(val) {
      var date = new Date(val);
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10
          ? "0" + (date.getDate() + 1)
          : date.getMonth() + 1) + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    formatDuring(mss) {
      var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = (mss % (1000 * 60)) / 1000;
      return hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 ";
    },

    changeDateFormat(time, format = "YYYY-MM-DD hh:mm:ss") {
      if (!time) return "";
      var datetime = new Date(time);
      var o = {
        "Y+": datetime.getFullYear(),
        "M+": datetime.getMonth() + 1,
        "D+": datetime.getDate(),
        "h+": datetime.getHours(),
        "m+": datetime.getMinutes(),
        "s+": datetime.getSeconds(),
        "q+": Math.floor((datetime.getMonth() + 3) / 3),
        S: datetime.getMilliseconds(),
      };
      if (/(Y+)/.test(format))
        format = format.replace(
          RegExp.$1,
          (datetime.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      return format;
    },
    onSearch(val) {
      this.$message.success(val);
    },
    actionUser(id) {
      this.$message.success(id);
    },
    actionMenu(id) {
      this.$message.success(id);
    },

    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      const value = e.target.value;
      const expandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, gData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
  },
};
</script>

<style lang="less" scoped>
.margin_bottom {
  margin-bottom: 16px;
}

.ant-layout-header {
  background: #03212100 !important;
}

.vtl {
  .vtl-drag-disabled {
    background-color: #d0cfcf;

    &:hover {
      background-color: #d0cfcf;
    }
  }

  .vtl-disabled {
    background-color: #d0cfcf;
  }
}
</style>
